How to create and use View in DB2 for i SQL |
A view is similar to Non-keyed LF and is used to access data in one or more table or views. We can create view by using the SELECT statement.
CREATE VIEW VIEW1LONGNAME FOR SYSTEM NAME VIEW1 AS SELECT * FROM PF1
Once the above CREATE VIEW query executed a view named VIEW1LONGNAME will be created and whose system object name will be VIEW1 using the clause FOR SYSTEM NAME. Without adding FOR SYSTEM NAME clause, system will generate the name like VIEW100001. We can do WRKOBJ on VIEW1 to search for this object. We can also change the data in table PF1 using view VIEW1.
Select * from VIEW1LONGNAME
Or
Select * from VIEW1
would give me the data of the VIEW1 based upon table PF1
EMPID EMPNAME MANAGERID E1 EMPNAME1 M1 E2 EMPNAME2 M2
CREATE VIEW VIEW1LONGNAME FOR SYSTEM NAME VIEW1 (ID, EMPNAME) AS SELECT EMPID concat '-' concat managerid, empname FROM pf1
Or
CREATE VIEW VIEW1LONGNAME FOR SYSTEM NAME VIEW1 AS SELECT EMPID concat '-' concat managerid as id, empname FROM pf1
Select * from VIEW1LONGNAME
Or
Select * from VIEW1
would give me the data of the VIEW1 based upon table PF1
ID EMPNAME E1 -M1 EMPNAME1 E2 -M2 EMPNAME2
We can create view by using the UNION keyword to combine results of two or more sub-select query and form a single view.
CREATE VIEW VIEW1LONGNAME for system name VIEW1 as (SELECT * FROM PF1 WHERE EMPID ='E1' UNION SELECT * FROM PF1B WHERE MANAGERID = 'M1' )